package com.huan.study.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 生产id
 *
 * @author huan.fu
 * @date 2024/8/12 - 12:27
 */
@Component
public class GeneratorIdApplicationRunner implements ApplicationRunner {

    private static final Logger log = LoggerFactory.getLogger(GeneratorIdApplicationRunner.class);
    private static final String KEY_PREFIX = "DD";
    private static final String VALUE = "1";
    @Resource
    private IdGenerator idGenerator;

    @Override
    public void run(ApplicationArguments args) throws Exception {

        ConcurrentHashMap<String, String> idsMap = new ConcurrentHashMap<>(10000);
        ExecutorService executor = Executors.newFixedThreadPool(5);
        CountDownLatch latch = new CountDownLatch(5);
        AtomicInteger count = new AtomicInteger(0);

        for (int i = 0; i < 5; i++) {
            executor.execute(() -> {
                for (int j = 0; j < 1000; j++) {
                    try {
                        TimeUnit.MILLISECONDS.sleep(1L);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    idsMap.put(String.valueOf(idGenerator.getNextId("DD")), VALUE);
                    count.incrementAndGet();
                }
                latch.countDown();
            });
        }

        latch.await();

        log.info("共产生: {}个id, 产生重复id: {}?", count.get(), count.get() != idsMap.size());
    }
}
